import queue
import time

import pyaudio

from voice.player.player import Player

CHANNELS = 1


class PyAudioPlayer(Player):

    def __init__(self, output_queue: queue.Queue, sample_rate: int = 16000, input_format=pyaudio.paInt16):
        super().__init__(output_queue)
        self.sample_rate = sample_rate
        self.format = input_format
        self._p = pyaudio.PyAudio()
        self.stream = None
        self.running = False
        self._get_format()

    def _get_format(self):
        if self.sample_rate >= 44100:
            self.format = pyaudio.paFloat32
        else:
            self.format = pyaudio.paInt16

    def start_player(self):
        if self.running:
            raise RuntimeError("Player already running")
        self.stream = self._p.open(format=self.format,
                                   channels=CHANNELS,
                                   rate=self.sample_rate,
                                   output=True)
        self.running = True
        self.thread.start()

    def stop_player(self):
        if not self.running:
            return
        self.running = False
        if self.stream:
            self.stream.stop_stream()
            self.stream.close()
        if self._p:
            self._p.terminate()
        if self.thread:
            self.thread.join()

    def _write(self, data):
        while self.running:
            try:
                if self.stream.is_active():
                    out_voice = self.output_queue.get_nowait()  # 使用非阻塞获取
                    print("播放音频---->", out_voice)
                    self.stream.write(out_voice)
                else:
                    time.sleep(0.3)  # 添加短暂休眠
            except queue.Empty:
                time.sleep(0.3)  # 添加短暂休眠
                continue
            except Exception as e:
                print(f"Write error: {e}")
